package threadpool;

import java.util.concurrent.*;

public class JucExecutorsDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        // 单线程执行器
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(()->{
            System.out.println("runalbe 执行了");
        });

        Future<String> future = executorService.submit(() -> {
            return "call result";
        });


        // 固定线程数量的线程池
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);
        fixedThreadPool.submit(() -> {
            System.out.println("runnable 执行了");
            return "xx";
        });


        // cached线程池的线程数是不固定的,可以动态增加工作线程
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        cachedThreadPool.submit(() -> {
            System.out.println("runnable 执行了");
            return "xx";
        });

        System.out.println("-------------------");

        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(4);
//        scheduledThreadPool.schedule(()->{
//            System.out.println("schedule 执行了");
//        },5,TimeUnit.SECONDS);

        // 固定周期调度;如果一个task执行时长超出了周期，则task完成后立马进行下一次task的执行
//        scheduledThreadPool.scheduleAtFixedRate(()->{
//            System.out.println(System.currentTimeMillis()/1000 +": schedule 执行了");
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//        },5,3,TimeUnit.SECONDS);



        // 固定延迟调度；下次task执行永远在上一个task完成后延迟固定时长
        scheduledThreadPool.scheduleWithFixedDelay(()->{
            System.out.println(System.currentTimeMillis()/1000 +": schedule 执行了");
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },0,3,TimeUnit.SECONDS);




    }
}
